#include <os/time.h>
#include <os/mm.h>
#include <os/irq.h>
#include <type.h>

LIST_HEAD(timers);//sleep队列已经进行过初始化。

uint64_t time_elapsed = 0;
uint32_t time_base = 0;
/*extern list_head timers;
typedef void (*TimerCallback) (void *parameter);
typedef struct timer
{
    list_node_t list;
    unint64_t timeout_tick;
    TimerCallback callback_func;
    void *parameter;
} timer_t;
这里做一个搬运，每个timer_t是一个计时器，内嵌一个睡眠队列。队列头
是 timers 。TimerCallback是一个返回值为空参数为指向空的指针的函数指针
为了保存创建的timer信息，我在pcb添加了新的域timer_t timer_p*/
void timer_create(TimerCallback func, void* parameter, uint64_t tick)
{//func应该是睡眠结束要返回也就是下一个要执行的函数，是do_unblock
    disable_preempt();//do_unblock只有一个参数，指向队列的指针
    list_add_tail(&(current_running->timer_p.list),&timers);
    current_running->timer_p.timeout_tick=get_ticks()+tick;
    current_running->timer_p.callback_func=func;
    current_running->timer_p.parameter=parameter;
    enable_preempt();
}

void timer_check()
{
    disable_preempt();

    /* TODO: check all timers
     *  if timeouts, call callback_func and free the timer.
     */
    list_node_t *cur=timers.next;

    while(cur!=&timers){
        if(list_entry(cur,timer_t,list)->timeout_tick<=get_ticks())//如果睡眠队列中一个进程时间到了执行它应该返回的函数
            {   
                cur=cur->next;
                list_entry(cur->prev,timer_t,list)->callback_func(list_entry(cur->prev,timer_t,list)->parameter);
                list_del(cur->prev);
            }
            else
                cur=cur->next;      
    }

    enable_preempt();
}

uint64_t get_ticks()
{
    __asm__ __volatile__(
        "rdtime %0"
        : "=r"(time_elapsed));
    return time_elapsed;
}

uint64_t get_timer()
{
    return get_ticks() / time_base;
}

uint64_t get_time_base()
{
    return time_base;
}

void latency(uint64_t time)//翻译一下，潜伏，方便理解
{
    uint64_t begin_time = get_timer();
//time是要潜伏的时间
    while (get_timer() - begin_time < time);
    return;
}
